package com.dwyinyuan.producer;

import com.dwyinyuan.utils.HttpUtils;
import org.jsoup.nodes.Document;

import java.util.concurrent.BlockingQueue;

public class Win4000Producer implements Runnable {

    private String name;
    private BlockingQueue<String> blockingQueue;

    public Win4000Producer(String name, BlockingQueue<String> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }

    private static final String URL = "http://www.win4000.com/meinv224485_%s.html";

    @Override
    public void run() {
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.setTimeout(10000);
        httpUtils.setWaitForBackgroundJavaScript(10000);
        try {
            String first_url = String.format(URL, 1);
            Document document = httpUtils.getHtmlPageResponseAsDocument(first_url);
            String first_pic = document.getElementsByAttributeValue("class", "pic-large")
                    .attr("src");
            String page = document.getElementsByAttributeValue("class", "ptitle").
                    get(0).getElementsByTag("em").text();

            Integer p = Integer.valueOf(page);

            blockingQueue.put(first_pic);
            for (int i = 1; i <= p; i++) {
                String url = String.format(URL, i);
                Document doc = httpUtils.getHtmlPageResponseAsDocument(url);
                String pic = doc.getElementsByAttributeValue("class", "pic-large")
                        .attr("src");

                blockingQueue.put(pic);
            }
            //消费者根据""退出while循环
            blockingQueue.put("");
            System.out.println("-----------------------------------");
            System.out.println(name + " is over");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
